import getDateTime from "@/utils/data.js";
import message from "api/message/message";
import {
	wss
} from '@/utils/ws.js'



export default {
	// 开启命名空间
	namespaced: true,
	// 数据
	state: {
		talkList: uni.getStorageSync(`messageList`) || [],
		Id: uni.getStorageSync("ID"),
		messageSession: uni.getStorageSync("messageSession") || [],
		tabBarBadgeCount: 0,
		isOpenSocket: false,
	},
	// 方法
	mutations: {
		//保存用户登录id
		saveId(state, id) {
			state.Id = id
			uni.setStorageSync("ID", id);
		},
		//删除登录id
		removeId(state) {
			state.Id = "";
			uni.removeStorageSync("ID");
		},
		
		// 更新现有会话的信息
		UPDATE_CONVERSATION(state, {
			consultationOrderId,
			messageSessionId,
			lastMessage,
			createTime,
			type,
			userIf
		}) {
			const existingConversation = state.messageSession.find(
				(conversation) => conversation.messageSessionId === messageSessionId
			);
			if (existingConversation) {
				// 更新会话的信息
				existingConversation.createTime = createTime;
				if (type == 1) {
					existingConversation.lastMessage = lastMessage;
				} else if (type == 2) {
					existingConversation.lastMessage = "【图片】";
				} else if (type == 3) {
					existingConversation.lastMessage = "【视频】";
				} else if (type == 4) {
					existingConversation.lastMessage = "撤回了一条信息";
				}
				// 不是自己发送的信息就给未读信息加一
				if (userIf != undefined && !userIf) {
					/* 修改 unreadCount */
					existingConversation.unreadCount += 1
					state.tabBarBadgeCount += 1;
					//设置红点
					uni.setTabBarBadge({
						index: 2, // 底部菜单栏的索引（从0开始）
						text: String(state.tabBarBadgeCount), // 要显示的文本（必须是字符串类型）
					});
				}
				/* 更新问诊订单 id */
				existingConversation.consultationOrderId = consultationOrderId
			}
			/* 设置值 */
			uni.setStorageSync("messageSession", state.messageSession)
		},
		/* 创建会话 */
		saveOffMessageStorage(state, {
			data,
			index
		}) {
			// 时间
			var timeStr = new Date()
			data.reverse().forEach(item => {
				if (item.groupId) {
					state.talkList.push({
						"groupId": item.groupId,
						"message": item
					});
					let session = {
						"messageSessionId": item.groupId,
						"groupId": item.groupId,
						"avatar": item.groupAvatar,
						"sessageName": item.groupName,
						"unreadCount": 0,
						"lastMessage": "您有群新信息！",
						"createTime": timeStr,
					}
					this.commit('m_message/INSERT_MESSAGE_SESSION', session);
				} else {
					state.talkList.push({
						"friendId": item.fromId,
						"message": item
					});
					let session = {
						'consultationOrderId': item.consultationOrderId,
						"messageSessionId": item.fromId,
						"friendId": item.fromId,
						"avatar": item.avatar,
						"sessageName": item.unickname,
						"unreadCount": 0,
						"lastMessage": "您有新信息！",
						"createTime": timeStr,
					}
					this.commit('m_message/INSERT_MESSAGE_SESSION', session);
				}
				state.tabBarBadgeCount += 1
			});
			//设置红点
			uni.setTabBarBadge({
				index: 2, // 底部菜单栏的索引（从0开始）
				text: String(state.tabBarBadgeCount), // 要显示的文本（必须是字符串类型）
			});
			uni.setStorageSync(`messageList`, state.talkList)
		},
		//创建会话
		INSERT_MESSAGE_SESSION(state, messageSession) {
			const isDuplicateMessage = state.messageSession.some(obj => obj.messageSessionId == messageSession
				.messageSessionId);
			if (isDuplicateMessage) {
				return
			}
			state.messageSession.push(messageSession);
			uni.setStorageSync("messageSession", state.messageSession)
		},
		/* 本地缓存 */
		saveMessageStorage(state, data) {
			let messageSessionId = "";
			let timeStr = new Date();
			let session = {}
			/*  */
			if(Object.keys(data).length === 0){
				console.log('return');
				return;
			}
			console.log('123');
			/* 消息 */
			/* 不能有空对象 */
			state.talkList = state.talkList.filter(obj => Object.keys(obj).length > 0);
			/* 消息id 不能重复 */
			const isDuplicateMessage = state.talkList.some(obj => obj.message.messageId == data.message.messageId);
			if (isDuplicateMessage) {
				return;
			}
			state.talkList.push(data);
			uni.setStorageSync(`messageList`, state.talkList)
			/*  */

			/* 会话 */
			if (data.groupId) {
				messageSessionId = data.groupId;
				session = {
					"messageSessionId": data.groupId,
					"groupId": data.groupId,
					"avatar": data.message.groupAvatar,
					"sessageName": data.message.groupName,
					"unreadCount": 0,
					"lastMessage": "",
					"createTime": timeStr,
				}
			}else if (data.friendId && !data.message.consultationOrderId ) {
				console.log('朋友');
				messageSessionId = data.friendId;
				/*  消息体 */
				session = {
					"messageSessionId": data.friendId,
					"friendId": data.friendId,
					"avatar": data.message.avatar,
					"sessageName": data.message.unickname,
					"unreadCount": 0,
					"lastMessage": "",
					"createTime": timeStr,
				}
				console.log(data.message, 'data.message.isUemployee');
			}
			else if (data.friendId && data.message.consultationOrderId) {
				return;
				console.log('医生');
				messageSessionId = data.friendId;
				/*  消息体 */
				session = {
					"consultationOrderId": data.message.consultationOrderId,
					"xxxxx": 'xxxxxxxxxxx',
					"messageSessionId": data.friendId,
					"friendId": data.friendId,
					"avatar": data.message.avatar,
					"sessageName": data.message.unickname,
					"unreadCount": 0,
					"lastMessage": "",
					"createTime": timeStr,
				}
				console.log(session, "session 医生会话");
				console.log(data.message, 'data.message.isUemployee');
			}
			let userIF = ''
			/*  */
			userIF = data.message.fromId == uni.getStorageSync("userInfo").userid
			
			
			/* 创建会话 */
			this.commit('m_message/INSERT_MESSAGE_SESSION', session);
			/* 更新会话信息 */
			this.commit('m_message/UPDATE_CONVERSATION', {
				/*  */
				"consultationOrderId": data.message?.consultationOrderId,
				/*  */
				"messageSessionId": messageSessionId,
				"lastMessage": data.message.content,
				"createTime": timeStr,
				"type": data.message.type,
				"userIf": userIF
			})
		},

		//计算红点
		addCount(state) {
			let count = 0;
			state.messageSession.forEach((item) => {
				count += item.unreadCount
			})
			state.tabBarBadgeCount = count;
			//设置红点
			uni.setTabBarBadge({
				index: 2, // 底部菜单栏的索引（从0开始）
				text: String(state.tabBarBadgeCount), // 要显示的文本（必须是字符串类型）
			});
		},
		//置顶
		TOP_CONVERSATION(state, messageSessionId) {
			const index = state.messageSession.findIndex(element => element.messageSessionId == messageSessionId);

			function swapArray(arr, index1, index2) {
				arr[index1] = arr.splice(index2, 1, arr[index1])[0];
				return arr;
			}
			state.messageSession = swapArray(state.messageSession, index, 0)
			state.messageSession[index].isTop = true;
			uni.setStorageSync("messageSession", state.messageSession)
		},
		// Vuex store mutation
		CANCEL_TOP_CONVERSATION(state, messageSessionId) {
			const index = state.messageSession.findIndex(element => element.messageSessionId === messageSessionId);

			if (index !== -1) {
				const topConversation = state.messageSession[index];
				state.messageSession.splice(index, 1); // Remove from current position
				state.messageSession.splice(1, 0, topConversation); // Insert at original position (index 1)
			}
		},
		/* 移除会话 */
		DELETE_MESSAGE(state) {
			state.messageSession = []
			uni.removeStorageSync("messageSession")
		},
		/* 主动将未读消息 变成 0 */
		changeConversationList(state, messageSessionId) {
			/* 会话id sessionId */
			state.messageSession.forEach((conversation) => {
				if (conversation.messageSessionId == messageSessionId) {
					console.log(conversation.unreadCount, 'conversation.unreadCount');
					if (conversation.unreadCount != 0) {
						state.tabBarBadgeCount -= conversation.unreadCount;
						console.log(state.tabBarBadgeCount, 'state.tabBarBadgeCount');
						uni.setTabBarBadge({
							index: 2, // 底部菜单栏的索引（从0开始）
							text: String(state.tabBarBadgeCount), // 要显示的文本（必须是字符串类型）
						});

						if (state.tabBarBadgeCount == 0) {
							console.log('移除红点');
							//移除红点
							uni.removeTabBarBadge({
								index: 2 // 底部菜单栏的索引（从0开始）
							});
						}

					}
					conversation.unreadCount = 0
				}
			})
			/* To do xxx */
			uni.setStorageSync("messageSession", state.messageSession)
		},
		/* 删除聊天内 一条文字 */
		DELETE_MessageOne(state, id) {
			/*  */
			const index = state.messageList.findIndex(element => element.id === id);
			/*  */
			if (index !== -1) {
				// console.log('删除');
				state.messageList.splice(index, 1)
			}
		},
		/* 删除会话记录一条*/
		DELETE_CONVERSATIONOne(state, id) {
			const existingConversation = state.messageSession.find(element => {
				element.messageSessionId == id
			});

			if (existingConversation) {
				existingConversation.lastMessage = '';
			}
			uni.setStorageSync("messageSession", state.messageSession)
		},
		/* 删除聊天记录 所有*/
		DELETE_MessageList(state, data) {
			console.log(data, "data");
			/* 删除群聊天记录 */
			if (data.groupId) {
				state.talkList = state.talkList.filter(
					message => message.groupId !== data.groupId
				);
				this.commit('m_message/DELETE_CONVERSATIONOne', data.groupId);
			} else {
				/* 删除单人记录 */
				state.talkList = state.talkList.filter(
					message => message.friendId !== data.friendId
				);
				this.commit('m_message/DELETE_CONVERSATIONOne', data.friendId);
			}

			uni.showToast({
				title: '清除成功',
				icon: "none"
			})
			uni.setStorageSync("messageList", state.talkList)
		},
		//删除会话
		DELETE_MESSAGE_LIST(state, messageSessionId) {
			const index = state.messageSession.findIndex(element => element.messageSessionId == messageSessionId);
			if (index !== -1) {
				console.log('删除');
				state.messageSession.splice(index, 1)
				uni.setStorageSync("messageSession", state.messageSession)
			}
		},
		/*已读未读 */
		UPDATE_STATUS(state, messageId) {
			for (let i = 0; i < state.talkList.length; i++) {

				if (state.talkList[i].message.messageId === messageId) {

					state.talkList[i].message.readStatus = 1;
					break;
				}
			}
			uni.setStorageSync(`messageList`, state.talkList)
		},
		/* 删除聊天内 一条文字 */
		DELETE_MessageOne(state, id) {
			const index = state.talkList.findIndex(element => element.message.messageId === id);

			if (index !== -1) {
				state.talkList.splice(index, 1)
			}
			uni.setStorageSync(`messageList`, state.talkList)
		},
		/* 删除会话记录一条*/
		DELETE_CONVERSATIONOne(state, id) {
			state.messageSession.find(element => {
				if (element.messageSessionId == id) {
					element.lastMessage = ''
				}
			});
			uni.setStorageSync(`messageSession`, state.messageSession);
		},
		/* 撤回消息 */
		RETRACT_MESSAGE(state, data) {
			const element = state.talkList.find(element => element.message.messageId == data.messageId);
			if (element) {
				element.message.isRetract = true;
			}
			this.commit('m_message/UPDATE_CONVERSATION', {
				"messageSessionId": data.messageId,
				"lastMessage": data.message.content,
				"createTime": timeStr,
				"type": 4,
				"userIf": false
			})
			uni.setStorageSync(`messageList`, state.talkList)
		},
		/* 是否撤回 */
		RETRACT_OFF_MESSAGE(state, {
			data,
			index
		}) {
			data.forEach(i => {
				let element = state.talkList.find(element => element.message.messageId == i.messageId);
				if (element) {
					element.message.isRetract = true;
				}
				console.log(state.talkList, "state.talkList.");
			})

			uni.setStorageSync(`messageList`, state.talkList)
		}
	},
	getters: {
		getTalkList(state) {
			return state.talkList;
		},
		getId(state) {
			return state.Id;
		},
		getIsOpenSocket(state) {
			return state.isOpenSocket;
		}
	},

	setters: {
		setTalkList(state, value) {
			state.talkList = value
		}
	},
}